# -*- coding: utf-8 -*-
"""
Created on 2015/12/28 21:14
@File: cookie_login.py
@Author: Liangrong Li
@ 模拟登陆案例 试验中 http://my.oschina.net/u/811744/blog/192087
"""
import urllib
import urllib2
import gzip
import cStringIO
import cookielib
import re

# filename = 'cookie_baidu.txt'
#
# cookie = cookielib.MozillaCookieJar(filename)
# opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))

login_url = 'http://zhanzhang.baidu.com'
user = 'liangyunwuxu'
pwd = 'wuxu139248'
headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3',
    'Cache-Control': 'max-age=0',
    'Connection': 'keep-alive',
    'Cookie': 'BAIDUID=DA2C1CD133344E60DB5E818B91320645:SL=0:NR=50:FG=1; BIDUPSID=DA2C1CD133344E60DB5E818B91320645; PSTM=1433159908; MCITY=-%3A; H_PS_PSSID=18502_1438_18241_18534_17948_18546_17000_17073_15804_11730; SITEMAPSESSID=7o84m7op4ujkf4i7m59rpbkmn0; lastIdentity=PassUserIdentity; __cas__st__=NLI; __cas__id__=0; Hm_lvt_031f28a54d603d47eb69f579fb3198a0=1451308048; Hm_lpvt_031f28a54d603d47eb69f579fb3198a0=1451311266',
    'Host': 'zhanzhang.baidu.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0',
}
postdata = {
    'codeString': '',
    'safeFlag': '0',
    'u': 'http://zhanzhang.baidu.com/dashboard/index',
    'isPhone': 'false',
    'detect': '1',
    'gid': '47EB310-C1B6-4794-8654-855207C2F54B',
    'staticPage': 'http://zhanzhang.baidu.com/v3Jump.html',
    'quick_user': '0',
    'logintype': 'basicLogin',
    'logLoginType': 'pc_loginBasic',
    'subpro': '',
    'idc': '',
    'loginMerge': 'true',
    'userName': user,
    'password': pwd,
    'verifyCode': '',
    'memberPass': ''
}
data = urllib.urlencode(postdata)
req = urllib2.Request(login_url, data, headers)
resp = urllib2.urlopen(req)
print dir(resp)
data = resp.read()

# 先进行解压操作
data = cStringIO.StringIO(data)
gzipper = gzip.GzipFile(fileobj=data)
html = gzipper.read()

# info = resp.info()
# status = resp.getcode()
# print info
# print status

with open('zhanzhang.html', 'w+') as f:
    f.write(html)
f.closed
# result = opener.open(login_url)
# resp =  result.read()
# # <div class="captcha-container">
# # <img width="120" height="30" alt="验证码" data-tip="s$t$看不清楚？换一张" class="js-refresh-captcha captcha" src="/captcha.gif?r=1451310013389">
# # </div>
# pattern = re.compile('div class="captcha-container">(.*?)</div>', re.S)
# # pattern = re.compile('<img class=\"js-refresh-captcha captcha\" .*? src="(.*?)">', re.S)
# checkcode_url = re.findall(pattern, resp)
# for i in checkcode_url:
#     print i